#include "GLHeaders.hpp"
#include "Texture.hpp"
#include "Color.hpp"
#include "Interpolation.hpp"
#include "../Global.hpp"
#include "Foreground.hpp"

Foreground_::Foreground_(void){
  InitTexture();
  InitList();
}

Foreground_::~Foreground_(void){
	glDeleteLists(list_id,1);
}

void Foreground_::Draw(void){
	glCallList(list_id);
}

void Foreground_::InitList(void){
	list_id = glGenLists(1); // create one DisplayList
	glNewList(list_id, GL_COMPILE);
	GLfloat coef = 1.0f;

  glPushAttrib(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_CURRENT_BIT|GL_TEXTURE_BIT);
  glDisable(GL_DEPTH_TEST);
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  glOrtho(0.0f, (GLdouble)window.width, 0.0f, (GLdouble)window.height, -1.0f, 1.0f);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();

	glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, text_id);
	glBegin(GL_TRIANGLES);
	glNormal3f( 0.0f, 0.0f, 1.0f); // Front Face
	glColor3f(1.0f, 1.0f, 1.0f);
 	glTexCoord2f(0.0f, 0.0f);glVertex3f( 0.0f, 0.0f, 0.0f);
	glTexCoord2f(coef, 0.0f);glVertex3f( (GLfloat)window.width, 0.0f, 0.0f);
	glTexCoord2f(coef, coef);glVertex3f( (GLfloat)window.width, (GLfloat)window.height, 0.0f);

	glTexCoord2f(coef, coef);glVertex3f( (GLfloat)window.width, (GLfloat)window.height, 0.0f);
	glTexCoord2f(0.0f, coef);glVertex3f( 0.0f, (GLfloat)window.height, 0.0f);
	glTexCoord2f(0.0f, 0.0f);glVertex3f( 0.0f, 0.0f, 0.0f);
	glEnd();
  glPopMatrix();
	glPopAttrib();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(GL_MODELVIEW);
	glEndList();
}
void Foreground_::InitTexture(void){
	Texture tex(window.width, window.height);

  for(int y=0; y < window.height+1; y+=64){
    for(int x=0; x < window.width+1; x+=64){
      tex = Texture::Add(tex.Line(
            Vector::Vector(x-4,y,0),
            Vector::Vector(x+4,y,0),
            Color::Color(0.0f, 0.4f, 0.0f, 1.0f),
            Color::Color(0.0f, 0.4f, 0.0f, 1.0f),
            1.0f, LINEAR),tex);
      tex = Texture::Add(tex.Line(
            Vector::Vector(x,y-4,0),
            Vector::Vector(x,y+4,0),
            Color::Color(0.0f, 0.4f, 0.0f, 1.0f),
            Color::Color(0.0f, 0.4f, 0.0f, 1.0f),
            1.0f, LINEAR),tex);
    }
  }
  /*
  tex = tex.Fill(
      Color::Color(0.0f, 0.0f, 0.0f, 1.0f), 
      Color::Color(0.0f, 0.0f, 0.0f, 0.5f), 
      Color::Color(1.0f, 0.0f, 0.0f, 0.2f),
      Color::Color(1.0f, 0.0f, 0.0f, 1.0f),
      NEAREST);
  */

  glGenTextures(1, &text_id);
	glBindTexture(GL_TEXTURE_2D, text_id);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, mizu);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLubyte *)tex.data);
}

